package com.wqd.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqd.model.common.constants.WemediaConstants;
import com.wqd.model.common.constants.WmNewsMessageConstants;
import com.wqd.model.common.dtos.PageResponseResult;
import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.common.enums.AppHttpCodeEnum;
import com.wqd.model.wemedia.dtos.WmNewsDto;
import com.wqd.model.wemedia.dtos.WmNewsPageReqDto;
import com.wqd.model.wemedia.pojos.WmMaterial;
import com.wqd.model.wemedia.pojos.WmNews;
import com.wqd.model.wemedia.pojos.WmNewsMaterial;
import com.wqd.model.wemedia.pojos.WmUser;
import com.wqd.utils.thread.WmThreadLocalUtil;
import com.wqd.wemedia.mapper.WmMaterialMapper;
import com.wqd.wemedia.mapper.WmNewsMapper;
import com.wqd.wemedia.mapper.WmNewsMaterialMapper;
import com.wqd.wemedia.service.WmNewsAutoScanService;
import com.wqd.wemedia.service.WmNewsService;
import com.wqd.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 查询全部文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //校验参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"缺少参数");
        }
        //分页健壮检查
        dto.checkParam();
        //获取当前登录人信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_INVALID);
        }

        //设置页码和页面大小
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());

        //分页条件设置
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //设置查询状态
        if(dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道精确查询
        if(dto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //时间范围查询
        if(dto.getBeginPubdate() != null && dto.getEndPubdate() != null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }
        //模糊查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //用户条件
        queryWrapper.eq(WmNews::getUserId,wmUser.getId());
        //结果按创建时间倒序排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        //查询
        page = page(page, queryWrapper);

        //返回结果
        ResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }


    @Autowired
    private WmNewsTaskService wmNewsTaskService;


    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //校验参数
        if(dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //如果是自动选项,先把类型置空,防止栈溢出
        if(dto.getType() == -1){
            dto.setType(null);
        }

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //获取dto封面图片
        List<String> images = dto.getImages();
        if(images.size() > 0){
            wmNews.setImages(StringUtils.join(images,","));
        }
        //保存或者更新(草稿或者提交都走这)
        saveOrUpdateNews(wmNews);
        //如果是草稿,直接返回
        if(dto.getStatus() == 0){
            return ResponseResult.okResult("保存草稿成功");
        }
        //获取内容中的图片集合
        List<String> imageList = getPictureFromContent(wmNews);
        //绑定内容图片和文章的关系
        contentImageToNews(imageList,wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
        //绑定封面图片和文章的关系
        coverImageToNews(imageList,wmNews,dto,WemediaConstants.WM_COVER_REFERENCE);

        //调用文章审核
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //延迟队列文章审核
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        return ResponseResult.okResult("success");
    }


    /**
     * 封面图片处理
     * @param imageList
     * @param wmNews
     * @param dto
     * @param type
     */
    private void coverImageToNews(List<String> imageList, WmNews wmNews, WmNewsDto dto, Short type) {
        //先获取封面图片
        List<String> coverImages = dto.getImages();

        //判断封面类型是否是自动选项
        if(dto.getType() == null){
            if(imageList.size() >= 1 && imageList.size() < 3){
                coverImages = imageList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if(imageList.size() >= 3){
                coverImages = imageList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else{
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(StringUtils.join(coverImages,","));
            updateById(wmNews);
        }
        //插入中间表
        saveNewsMaterial(coverImages,wmNews,type);
    }


    /**
     * 内容图片处理
     * @param imageList
     * @param wmNews
     * @param type
     */
    private void contentImageToNews(List<String> imageList, WmNews wmNews, Short type) {
        saveNewsMaterial(imageList,wmNews,type);
    }


    /**
     * 抽取方法: 用于保存中间表关系
     * @param imageList
     * @param wmNews
     * @param type
     */
    private void saveNewsMaterial(List<String> imageList, WmNews wmNews, Short type) {
        //判断数据
        if(imageList != null && imageList.size() > 0){
            //根据地址集合去查询素材表,获取素材集合
            List<WmMaterial> materialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //过滤出素材id集合
            List<Integer> materialIdList = materialList.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量绑定关系到中间表
            wmNewsMaterialMapper.saveRelations(materialIdList,wmNews.getId(),type);
        }
    }


    /**
     * 封装方法: 用于抽取内容图片
     * @param wmNews
     * @return
     */
    private List<String> getPictureFromContent(WmNews wmNews) {
        List<String> imageList = new ArrayList<>();
        //内容
        String content = wmNews.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                imageList.add((String) map.get("value"));
            }
        }
        return imageList;
    }


    /**
     * 封装方法: 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        //补充数据
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        //判断此文章是修改还是新增(有id是修改的)
        if(wmNews.getId() != null){
            //修改的,把原来的删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            //修改文章表
            updateById(wmNews);
        }else{
            save(wmNews);
        }
    }


    /**
     * 文章编辑回显
     * @param id
     * @return
     */
    @Override
    public ResponseResult showNews(Integer id) {
        WmNews wmNews = getById(id);
        if(wmNews != null){
            return ResponseResult.okResult(wmNews);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNews(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if(wmNews.getStatus() == 9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章已发布,不能删除");
        }
        //删除
        return ResponseResult.okResult(removeById(id));
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    /**
     * 文章上架下架
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章id不可缺少");
        }

        //查询文章
        WmNews wmNews = getById(dto.getId());

        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        if(wmNews.getStatus() == null || wmNews.getStatus() != 9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态,不能上下架");
        }

        //修改文章状态 ---- 如果是上架改为下架,如果是下架改为上架
        wmNews.setEnable((short) (wmNews.getEnable() == 1 ? 0 : 1));
        boolean flag = updateById(wmNews);

        if (flag) {
            //发送消息,通知article端修改文章配置
            if(wmNews.getArticleId() != null){
                Map<String,Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",wmNews.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            }
        }

        return ResponseResult.okResult("修改状态成功");
    }

}
